﻿using System;
using System.Collections.Generic;
using System.Text;
using Listen1.Entity;
using System.Net;
using System.IO;
using NSoup;
using NSoup.Nodes;
using NSoup.Select;
namespace Listen1.WebRequest
{
    public class NetEaseSongSheet : ISongSheet
    {
       
        public IList<SongSheet> GetList_FromSite(int pagesize=0)
        {
            IList<SongSheet> list = new List<SongSheet>(100);
            HttpWebRequest webRequest = HttpWebRequest.CreateHttp("http://music.163.com/discover/playlist/?order=hot&cat=全部&limit=35&offset=" + pagesize);
            webRequest.Referer = "http://music.163.com/#";
            webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36";
            HttpWebResponse webResponse= (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream());
            string content= reader.ReadToEnd();
            Document document = NSoupClient.Parse(content);
            Element container = document.GetElementById("m-pl-container");
            
            foreach (Element item in container.Children)
            {
                Element title = item.GetElementsByClass("tit")[0];
                SongSheet sheet = new SongSheet();
                sheet.Thumb = item.GetElementsByClass("j-flag")[0].Attr("src");
                sheet.Title = title.Html();
                sheet.Author = item.GetElementsByClass("nm-icn")[0].Html();
                sheet.Url = "http://music.163.com/" + title.Attr("href").Trim('/');
                sheet.Id = sheet.Url.Substring(sheet.Url.LastIndexOf("id=") + 3);
                list.Add(sheet);
            }
            
            return list;

        }

        public IList<SongSheet> GetList(int pagesize = 0)
        {
            IList<SongSheet> list = new List<SongSheet>(100);
            HttpWebRequest webRequest = HttpWebRequest.CreateHttp("http://music.163.com/discover/playlist");
            webRequest.Referer = "http://music.163.com/#";
            
            webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36";
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream());
            string content = reader.ReadToEnd();
            Document document = NSoupClient.Parse(content);
            Element container = document.GetElementById("m-pl-container");

            foreach (Element item in container.Children)
            {
                Element title = item.GetElementsByClass("tit")[0];
                SongSheet sheet = new SongSheet();
                sheet.Thumb = item.GetElementsByClass("j-flag")[0].Attr("src");
                sheet.Title = title.Html();
                sheet.Author = item.GetElementsByClass("nm-icn")[0].Html();
                sheet.Url = "http://music.163.com/" + title.Attr("href").Trim('/');
                sheet.Id = sheet.Url.Substring(sheet.Url.LastIndexOf("id=") + 3);
                list.Add(sheet);
            }

            return list;

        }



        public void ReadSheetDetail(SongSheet sheet)
        {
            HttpWebRequest webRequest = HttpWebRequest.CreateHttp(sheet.Url);
            webRequest.Referer = "http://music.163.com/#";
            webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36";
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream());
            string content = reader.ReadToEnd();
            Document document = NSoupClient.Parse(content);
            Element minfo = document.GetElementsByClass("m-info")[0];
            sheet.Author = minfo.GetElementsByClass("name")[0].GetElementsByTag("a")[0].Html();
            sheet.AuthorPhoto = minfo.GetElementsByClass("face")[0].GetElementsByTag("img")[0].Attr("src");
            sheet.CreateDate = Convert.ToDateTime(minfo.GetElementsByClass("time")[0].Html().Substring(0, 10));
            StringBuilder sb = new StringBuilder();
            foreach (Element item in minfo.GetElementsByClass("tags")[0].GetElementsByTag("i"))
            {
                sb.Append("、"+item.Html());
            }
            if (sb.Length>0)
            {
                sb = sb.Remove(0,1);
            }
            sheet.Tag = sb.ToString();
            Element songTab = document.GetElementsByClass("n-songtb")[0];
            sheet.PlayNum = Convert.ToInt32(songTab.GetElementById("play-count").Html());
            sheet.SongNum = Convert.ToInt32(songTab.GetElementById("playlist-track-count").Html());

            List<Song> songList = new List<Song>();
            foreach (Element item in document.GetElementById("song-list-pre-cache").GetElementsByClass("f-hide")[0].GetElementsByTag("li"))
            {
                Element ele= item.Children[0];
                Song song = new Song();
                
                song.Title= ele.Text();
                song.Url = "http://music.163.com/" + ele.Attr("href").Trim('/');
                song.Id = song.Url.Substring(song.Url.LastIndexOf("id=") + 3);                
                songList.Add(song);
            }
            sheet.SongList = songList;
        }



        public void ReadSongDetail(SongSheet sheet)
        {
            foreach (Song item in sheet.SongList)
            {
                if (!string.IsNullOrEmpty(item.Lyric) || !string.IsNullOrEmpty(item.SongUrl))
                {
                    continue;
                }
                ReadSongDetail(item);
            }
        }

        public void ReadSongDetail(Song song)
        {
            HttpWebRequest webRequest = HttpWebRequest.CreateHttp(song.Url);
            webRequest.Referer = "http://music.163.com/#";
            webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36";
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream());
            string content = reader.ReadToEnd();
            Document document = NSoupClient.Parse(content);
            Element lycinfo = document.GetElementsByClass("m-lycifo")[0];
            song.Thumb= lycinfo.GetElementsByClass("u-cover")[0].GetElementsByTag("img")[0].Attr("data-src");
            Elements fc7= lycinfo.GetElementsByClass("s-fc7");
            song.Singer = fc7[0].Html();
            song.Album =fc7[1].Html();
            song.Lyric = document.GetElementById("lyric-content").Html();

        }
        public bool Download(Song song,string localpath)
        {
                HttpWebRequest webRequest = HttpWebRequest.CreateHttp("http://music.163.com/song/media/outer/url?id=" + song.Id + ".mp3");
                webRequest.Referer = "http://music.163.com/#/song?id=" + song.Id;
                webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36";
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                if (string.IsNullOrEmpty(localpath))
                {
                    if (webResponse.ResponseUri==null)
                    {
                        return false;
                    }
                    song.SongUrl= webResponse.ResponseUri.AbsoluteUri;
                    webResponse.Close();
                    return true;
                }
                Stream reader = webResponse.GetResponseStream();
                int count = 1024;
                byte[] buffer = new byte[count];
                int b = 0;
                FileStream fs = new FileStream(localpath, FileMode.CreateNew);
                while ((b = reader.Read(buffer, 0, count)) > 0)
                {
                    fs.Write(buffer, 0, b);
                }
                fs.Flush();
                fs.Close();
                reader.Close();
                reader.Dispose();

                return true;
            
        }

    }
}
